package demo_0713;

import java.util.Comparator;
import java.util.PriorityQueue;
class IntCmp implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2 - o1;
    }
}
public class T1_0330 {
//    public int[] smallestK(int[] arr, int k) {
//        if (arr.length <= 0 || k <= 0) return new int[0];
//        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
//        for (int i = 0; i < arr.length; i++) {
//            priorityQueue.offer(arr[i]);
//        }
//        int[] array = new int[k];
//        for (int i = 0; i < k; i++) {
//            array[i] = priorityQueue.poll();
//        }
//        return array;
//    }

    public int[] smallestK(int[] arr, int k) {
       if (arr.length <= 0 || k <= 0) return new int[0];
       PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new IntCmp());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            if (arr[i] < priorityQueue.peek()) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        int[] array = new int[k];
        for (int i = 0; i < k; i++) {
            array[i] = priorityQueue.poll();
        }
        return array;
    }
}
